package com.cip.admin.dao.impl;

import java.util.List;

import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.cip.admin.dao.UserDao;
import com.cip.admin.model.Institute;
import com.cip.admin.model.User;
import com.cip.common.util.SecurityUtil;

/**
 * This class interacts with Spring's HibernateTemplate to save/delete and
 * retrieve User objects.
 *
 * @author <a href="mailto:matt@raibledesigns.com">Matt Raible</a>
 *   Modified by <a href="mailto:dan@getrolling.com">Dan Kibler</a>
 *   Extended to implement Acegi UserDetailsService interface by David Carter david@carter.net
 *   Modified by <a href="mailto:bwnoll@gmail.com">Bryan Noll</a> to work with 
 *   the new BaseDaoHibernate implementation that uses generics.
*/
public class UserDAOImpl extends GenericDAOImpl<User, Integer> implements UserDao, UserDetailsService {

    /**
     * Constructor that sets the entity to User.class.
     */
    public UserDAOImpl() {
        super(User.class);
    }

    /**
     * {@inheritDoc}
     */
    @SuppressWarnings("unchecked")
    public List<User> getUsers() {
        return getHibernateTemplate().find("from User u order by upper(u.username)");
    }

    /**
     * {@inheritDoc}
     */
    public User saveUser(User user) {
        if (log.isDebugEnabled()) {
            log.debug("user's id: " + user.getId());
        }
        getHibernateTemplate().saveOrUpdate(user);
        // necessary to throw a DataIntegrityViolation and catch it in UserManager
        getHibernateTemplate().flush();
        return user;
    }

    /**
     * Overridden simply to call the saveUser method. This is happenening 
     * because saveUser flushes the session and saveObject of BaseDaoHibernate 
     * does not.
     *
     * @param user the user to save
     * @return the modified user (with a primary key set if they're new)
     */
    @Override
    public User save(User user) {
        return this.saveUser(user);
    }

    /** 
     * {@inheritDoc}
    */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        List users = getHibernateTemplate().find("from User where username=?", username);
        if (users == null || users.isEmpty()) {
            throw new UsernameNotFoundException("user '" + username + "' not found...");
        } else {
            return (UserDetails) users.get(0);
        }
    }

    /** 
     * {@inheritDoc}
    */
    public String getUserPassword(String username) {
        HibernateTemplate hibernateTemplate = getHibernateTemplate();
        String query = "select userInfo.password from User as userInfo where userInfo.username='"+username+"'";
        List<Object> pwd = hibernateTemplate.find(query);
        return String.valueOf(pwd.get(0));
    }
    
    @SuppressWarnings("unchecked")
	public List<User> getAllCandidates() throws Exception{
    	User loggedinUser = SecurityUtil.getLoggedInUser();
    	Integer tenantId=loggedinUser.getTenantId();
    	String query;
        if(tenantId > 0){
        	query = "select userInfo from User as userInfo JOIN userInfo.roles r where r.name ='ROLE_USER' and userInfo.tenantId="+tenantId;
        }else{
        	query = "select userInfo from User as userInfo JOIN userInfo.roles r where r.name ='ROLE_USER'";
        }
        return getHibernateTemplate().find(query);
    }
    
    public User saveOrUpdateUser(User user) throws Exception {
		getHibernateTemplate().saveOrUpdate(user);
		return user;
	}
    
    public List<User> getAllCandidatesByClass(int classId, int sectionId) throws Exception{
    	User loggedinUser = SecurityUtil.getLoggedInUser();
    	Integer tenantId=loggedinUser.getTenantId();
    	String query = "select userInfo from User as userInfo where userInfo.tenantId="+tenantId+" and userInfo.classYear="+classId+" and userInfo.section="+sectionId;
    	return getHibernateTemplate().find(query);    	
    }
    
    public int getLastCandidateId(int classId, int sectionId) throws Exception{
    	User loggedinUser = SecurityUtil.getLoggedInUser();
    	List<Integer> results = null;
    	Integer tenantId=loggedinUser.getTenantId();
    	String query = "select max(userInfo.id) from User as userInfo where userInfo.tenantId="+tenantId+" and userInfo.classYear="+classId+" and userInfo.section="+sectionId;
    	results = getHibernateTemplate().find(query);
    	if(results != null && results.size() > 0 && results.get(0) != null){
    		return results.get(0);    	
    	}else{
    		return 0;
    	}
    	
    }
    
    
}
